package com.gdth.bank.model;

import java.util.List;

import rx.Observable;
import rx.Subscriber;

import com.gdth.bank.BankApplication;
import com.gdth.bank.utils.AppUtil;
import com.gdth.bank.utils.SharedPreferencesUtil;
import com.gdth.database.bean.TXtBm;
import com.gdth.database.bean.TXtBmDao;
import com.gdth.http.method.HttpMethodServlet;
import com.gdth.resource.Constant;
import com.gdth.utils.GsonUtil;

import org.greenrobot.greendao.query.QueryBuilder;


public class TXtBmModel {
	
	public Observable<String> getBm() {
		TXtBmDao dao = BankApplication.getDaoSession().getTXtBmDao();
		QueryBuilder<TXtBm> qb = dao.queryBuilder();
		qb.where(TXtBmDao.Properties.SwbmBj.eq("0"), qb.and(TXtBmDao.Properties.Zt.eq(1), TXtBmDao.Properties.Bh.notEq(Constant.jgm)));
		List<TXtBm> mList = qb.list();
		
		if (mList == null || mList.size() == 0)
			return getBmOnline();
		else {
			return getBmLocal();
		}
	}
	
	public Observable<String> getBmLocal(){
		return Observable.create(new Observable.OnSubscribe<String>() {

			@Override
			public void call(Subscriber<? super String> arg0) {
				// TODO Auto-generated method stub
				TXtBmDao dao = BankApplication.getDaoSession().getTXtBmDao();
				QueryBuilder<TXtBm> qb = dao.queryBuilder();
				qb.where(TXtBmDao.Properties.SwbmBj.eq("0"), qb.and(TXtBmDao.Properties.Zt.eq(1), TXtBmDao.Properties.Bh.notEq(Constant.jgm)));
				List<TXtBm> mList = qb.list();
				if (mList == null){
					arg0.onError(null);
				} else {
					arg0.onNext(GsonUtil.getGson().toJson(mList));
					arg0.onCompleted();
				}
			}
		});
	}
	
	/**
	 * 获取全部机构
	 * @return
	 */
	public Observable<String> getBmOnline(){
		return HttpMethodServlet.getInstance().getAllBm("content");
	}
	
	/**
	 * 保存所有部门信息
	 * @param mList
	 */
	public void saveBm(List<TXtBm> mList){
		//保存到缓存
		String json = GsonUtil.getGson().toJson(mList);
		SharedPreferencesUtil.saveSharePreference(AppUtil.SHARE_Application, AppUtil.SHARE_DATA_BM, json);
		TXtBmDao dao = BankApplication.getDaoSession().getTXtBmDao();
		dao.deleteAll();
		dao.insertInTx(mList);
	}
	
	public Observable<List<TXtBm>> getAllBm(String val){
		return Observable.create(new Observable.OnSubscribe<List<TXtBm>>() {

			@Override
			public void call(Subscriber<? super List<TXtBm>> arg0) {
				// TODO Auto-generated method stub
				TXtBmDao dao = BankApplication.getDaoSession().getTXtBmDao();
				QueryBuilder<TXtBm> qb = dao.queryBuilder();
				qb.where(TXtBmDao.Properties.SwbmBj.eq("0"), qb.and(TXtBmDao.Properties.Zt.eq(1), TXtBmDao.Properties.Bh.notEq(Constant.jgm)));
				List<TXtBm> mList = qb.list();
				if (mList == null){
					arg0.onError(null);
				} else {
					arg0.onNext(mList);
					arg0.onCompleted();
				}
			 
			}
		});
	}
	
	
}
